console.log("webAgent say hello ");
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
		typeof define === 'function' && define.amd ? define( ["jquery"], factory):
			(global.webAgent = factory());
}(this, function () {

	//对象
	var self = null;
	var socket = null;
	var loginTimer = null;

	//是否在线
	var isOnline = false;
	//单步类型  1转接 2会议
	var  singleStepType = null;

	var agent = {};
	var config = {
		serverUrl: ''
	};
	/**
	 * 座席端相关配置
	 */
	var option = {
	};
	var agentDefault = {
		agentId : '',
		agentDn : '',
		agentName : '',
		agentType : '5',
		entId : '',
		acdAgentPassword : '',
		agentDnPwd : '',
		status: -1,
		isLogin: false
	};
	var configDefault = {
		serverUrl : '',		// 配置服务地址
		proxyUrl : '',		// 代理服务地址
		autoRTCAnswer : false,	// RTC是否自动应答
		wsUrl : '',		// WebSocket服务器
		udpUrl : '',		// SIP代理URL
		stunServers : '',	// ICE服务器
		autoLogin : true,	// 是否自动签入
		debug : true		// 启用调试
	};

	var webRTCClient;

function webAgent(){

	self = this;

	this.initialize = function (data) {
         var that = this;
		if(data.proxyUrl!=null&&data.proxyUrl!=''){
			option.proxyUrl =data.proxyUrl+"?entId="+data.entId;
		}
		option.entId = data.entId;
		option.agentId = data.agentId;
		if(data.agentType === '5' || data.agentType === 5 ){
			option.agentDn = "sip:"+data.agentDn;
		}else if(data.agentType === '2' || data.agentType === 2 ){
			option.agentDn =  "sip:"+data.agentDn;
		}else {
			option.agentDn =  "tel:"+data.agentDn;
		}
		option.agentDnPwd = data.agentDnPwd;
		option.agentName = data.agentName;
		option.acdAgentPassword = data.acdAgentPassword;
		option.agentType = data.agentType;
		option.serverUrl = data.serverUrl;
		option.wsUrl = data.wsUrl;
		option.udpUrl = data.udpUrl;
		option.stunServers = data.stunServers;
		option.autoRTCAnswer = data.autoRTCAnswer;
		that.setOption(option);
		if(data.agentType === '5'){
			webRTCClient = new webrtcPhone();
			webRTCClient.init({
				serverUrl: data.serverUrl,
				name: data.agentName,
				exten: data.agentDn,
				password:  data.agentDnPwd,
				wssUrl:  data.wsUrl,
				udpUrl:  data.udpUrl,
				stunServers:  data.stunServers,
				entId: data.entId
			});
		}


	}

	//启动服务
	this.start= function(){

		setDefault();
		connect();
		if(option.agentType === '5') {
			getSipMessage.call(this, webRTCClient)
		}
	}

	function getSipMessage(webRTCClient){
		webRTCClient.onEvent = function (event) {

			console.log("listener--SIPml-Message--", event, event.type, event.description);
			if(event.type === 'terminated' && event.description === 'Forbidden') {// 被禁止了
				console.log('sipml连接终止未成功-501');
				var errorCode = '-501';
				var errorDesc = 'Err_IContact_SIPml_' + (event.type) + '_' + (event.description);
				var errormsg = '媒体服务连接失败,SIP:' + event.type + '，请重新登录！';
				getEvent(createAgnetSIPErrorEvent(errorCode, errorDesc, errormsg));
			}
		}
	}

	//停止服务
	this.stop = function() {
        var that = this;
		if (agent.isLogin) {
			that.logout();
		}
		setTimeout(function() {
			if (socket && isOnline) {
				socket.close();
			}
		}, 100);
	}

	/**
	 * 登录
	 * @returns {boolean}
	 */
	 this.login = function() {
		console.log('web-phone登录login', agent)
		return sendCommand(createLoginCommand(agent));
	}

	/**
	 * 登出
	 * @returns {boolean}
	 */
	this.logout = function () {
		if (agent.isLogin) {
			agent.isLogin = false;
			return sendCommand(createLogoutCommand(agent.agentId));
		}
		return false;
	}

	/**
	 * 置忙
	 * @returns {boolean}
	 */
	this.notReady = function () {
		if (agent.isLogin) {
			return sendCommand(createNotReadyCommand(agent.agentId));
		}
		return false;
	}
	/**
	 * 置闲
	 * @returns {boolean}
	 */
	this.ready = function() {
		if (agent.isLogin) {
			return sendCommand(createReadyCommand(agent.agentId));
		}
		return false;
	}
	/**
	 * 重置坐席状态
	 * @param state
	 * @returns {boolean}
	 */
	this.agentStateReset = function(state){
		if (agent.isLogin) {
			return sendCommand(createAgentStateResetCommand(agent.agentId,state));
		}

	}
	/**
	 * 外呼
	 * @param destType 外呼类型
	 * @param destDesc //外呼号码
	 * @param explicitNum //外显号码
	 * @returns {boolean}
	 */
	this.makeCall = function(destType, destDesc, explicitNum) {
		return sendCommand(createMakeCallCommand(agent.agentId, destType, destDesc, explicitNum));
	}

	/**
	 * 应答
	 * @returns {boolean}
	 */
	this.doAnswer = function() {
		if (agent.isLogin) {
			if(option.agentType === '5'){
				webRTCClient.answer();
			}
			//return sendCommand(createAnswerCommand(agent.agentId, agent.agentDn));
		}
		return false;
	}

	/**
	 * 挂断
	 * @returns {boolean}
	 */
	this.doHangup = function() {
		if (agent.isLogin) {
			return sendCommand(createHangupCommand(agent.agentId, agent.agentDn));
		}
		return false;
	}

	/**
	 * 保持
	 * @returns {boolean}
	 */
	this.doHold = function() {
		if (agent.isLogin) {
			return sendCommand(createHoldCommand(agent.agentId, agent.acdAgentPassword));
		}
		return false;
	}

	/**
	 * 接回
	 * @returns {boolean}
	 */
	this.doRetrive = function() {
		if (agent.isLogin) {
			return sendCommand(createRetrieveCommand(agent.agentId, agent.acdAgentPassword));
		}
		return false;
	}

	/**
	 * 咨询
	 * @param consultType 咨询类型 1是分机 2-外线
	 * @param destDesc 咨询号码
	 * @param sessionId 通话标识
	 * @returns {boolean}
	 */
	this.doConsulting = function(consultType, destDesc, sessionId) {

		if (agent.isLogin) {
			return sendCommand(createConsultingCommand(agent.agentId, agent.acdAgentPassword, sessionId,consultType, destDesc));
		}
		return false;
	}

	/**
	 * 咨询接回
	 * @returns {boolean}
	 */
	this.reconnectCall = function() {
		if (agent.isLogin) {
			return sendCommand(createReconnectCallCommand(agent.agentId, agent.agentDn));
		}
		return false;
	}

	//单步 destType 1-会议、2-转接
	this.doSingleStep = function(consultType,destId,destDesc, sessionId) {
		var that = this;
		singleStepType = destId;
		return that.doConsulting(consultType, destDesc, sessionId);
	}

	/**
	 * 会议
	 * @returns {boolean}
	 */
	this.doMeeting = function() {
		if (agent.isLogin) {
			return sendCommand(createMeetingCommand(agent.agentId, agent.acdAgentPassword));
		}
		return false;
	}
	/**
	 * 转接
	 * @returns {boolean}
	 */
	this.doAdressShift = function() {

		if (agent.isLogin) {

			sendCommand(createAdressShiftCommand(agent.agentId, agent.acdAgentPassword));
		}
		return false;
	}

	/**
	 * 转IVR
	 * @param callData 随路数据
	 */
	this.doTransferIVR = function(callData) {


		if (agent.isLogin) {
			return sendCommand(createTransferIVRCommand(agent.entId, agent.agentId,agent.acdAgentPassword, callData));
		}
		return false;
	}

	/**
	 * 密语
	 * @param sessionId 通话标识
	 * @param destType//destType (1开始 2结束)
	 * @returns {boolean}
	 */
	this.whisper = function (sessionId,destType){

		if (agent.isLogin) {
			return sendCommand(createWhisperCommand(agent.agentId, agent.acdAgentPassword, sessionId,destType));
		}
		return false;
	}

	/**
	 * 坐席协作
	 * @param dataKey
	 * @param dataValue
	 * @returns {boolean}
	 */
	this.doAssistService = function(dataKey, dataValue){

		if (agent.isLogin) {
			return sendCommand(createAssistServiceCommand(agent.agentId, agent.acdAgentPassword, dataKey, dataValue));
		}
		return false;
	}
	/**
	 * DTMF按键
	 * @param DTMF
	 * @returns {boolean}
	 */
	this.sendDTMF = function(DTMF) {
		console.log('web-agent,js-----DTMF按键---', DTMF)
		if (agent.isLogin) {
			// return sendCommand(createSendDTMFCommand(agent.agentId, agent.agentDn, DTMF));
			webRTCClient.sipSendDTMF(DTMF);
		}
		return false;
	}

	/**
	 * 监听
	 * @param destAgentId 目标坐席工号
	 * @returns {boolean}
	 */
	this.doListen = function(destAgentId) {
		if (agent.isLogin) {
			//httpGet(buildHttpUrl(config.setautoUrl));
			return sendCommand(createListenCommand(agent.agentId, agent.acdAgentPassword, destAgentId));
		}
		return false;
	}
	/**
	 * 强插
	 * @returns {boolean}
	 */
	this.doInsert = function() {
		if (agent.isLogin) {
			//httpGet(buildHttpUrl(config.setautoUrl));
			return sendCommand(createInsertCommand(agent.agentId));
		}
		return false;
	}

	/**
	 * 强拆
	 * @returns {boolean}
	 */
	this.doDrop = function(destAgentId) {
		if (agent.isLogin) {
			return sendCommand(createDropCommand(destAgentId));
		}
		return false;
	}
	/**
	 * 设置随路数据
	 * @param sessionId 通话标识
	 * @param dataKey 随路数据键
	 * @param dataValue 随路数据值
	 * @returns {boolean}
	 */
	this.setCallData = function(sessionId,dataKey, dataValue) {
		if (agent.isLogin) {
			return sendCommand(createSetCallDataCommand(agent.agentId,sessionId, dataKey, dataValue));
		}
		return false;
	}

	/**
	 * 获取随路数据
	 * @param sessionId 通话标识
	 * @param dataKey 随路数据键
	 * @returns {boolean}
	 */
	this.getCallData = function(sessionId,dataKey) {

		if (agent.isLogin && dataKey && sessionId) {

			return sendCommand(createGetCallDataCommand(agent.agentId,sessionId, dataKey));
		}

		return false;
	}

	/**
	 * 获取坐席状态
	 * @param agentId 坐席工号
	 * @returns {boolean}
	 */
	this.getAgentState = function(agentId) {
		if (agent.isLogin) {
			return sendCommand(createGetAgentStateCommand(agent.entId,agentId,agent.acdAgentPassword,''));
		}

		return false;
	}

	/**
	 * 获取坐席列表
	 * @returns {boolean}//0 咨询 2监听 3单步
	 */
	this.getAgentListData = function(showType){
		if (agent.isLogin) {
			let agentState = (showType == 0) ? 101 : (showType == 2) ? 102 : '';
			return sendCommand(createAgentListCommand(agent.entId, agentState, agent.agentId));
		}
		return false;
	}

	/**
	 * 获取外显号码列表
	 * @returns {boolean}
	 */
	this.getAgentDialCaller = function(){
		if (agent.isLogin) {
			return sendCommand(createAgentDialCallerCommand(agent.entId,agent.agentId));
		}
		return false;
	}

	// 开始静音
	this.doStartMute = function() {
		if (agent.isLogin && agent.agentType === '5') {

			webRTCClient.sipToggleMute(true);
			return true;
		}
		return false;
	};

	// 结束静音
	this.doStopMute = function() {
		if (agent.isLogin && agent.agentType === '5') {

			webRTCClient.sipToggleMute(false);
			return true;
		}
		return false;

	};

	this.getOption = function(field) {
		if (field == undefined) {
			return {
				agentId : agent.agentId,
				agentDn : agent.agentDn,
				agentName : agent.agentName,
				agentType : agent.agentType,
				entId : agent.entId,
				acdAgentPassword : agent.acdAgentPassword,
				agentDnPwd : agent.agentDnPwd,
				status: agent.status,
				serverUrl : config.serverUrl,
				proxyUrl : config.proxyUrl,
				wsUrl : config.wsUrl,
				udpUrl : config.udpUrl,
				iceServers : config.iceServers,
				autoLogin : config.autoLogin,
				debug : config.debug,
				autoRTCAnswer: config.autoRTCAnswer
			};
		} else {
			var value = agent[field];

			if (value == undefined) {
				value = config[field];
			}

			return value;
		}
	}

	this.setOption = function(option) {
		option = option || {};
		console.log('-===========setoption', option, agent)
		if (!agent.isLogin || option.agentDn) {
			if (option.hasOwnProperty('agentId')) {
				agent.agentId = (option.agentId || '') + '';
			}

			if (option.hasOwnProperty('agentDn')) {
				agent.agentDn = (option.agentDn || '') + '';
			}

			if (option.hasOwnProperty('agentName')) {
				agent.agentName = (option.agentName || '') + '';
			}

			if (option.hasOwnProperty('agentType')) {
				agent.agentType = option.agentType;
			}

			if (option.hasOwnProperty('entId')) {
				agent.entId = (option.entId || '') + '';
			}

			if (option.hasOwnProperty('acdAgentPassword')) {
				agent.acdAgentPassword = (option.acdAgentPassword || '') + '';
			}
			if (option.hasOwnProperty('agentDnPwd')) {
				agent.agentDnPwd = (option.agentDnPwd || '') + '';
			}
		}

		if (option.hasOwnProperty('serverUrl')) {
			config.serverUrl = (option.serverUrl || '') + '';
		}

		if (option.hasOwnProperty('proxyUrl')) {
			config.proxyUrl = (option.proxyUrl || '') + '';
		}

		if (option.hasOwnProperty('wsUrl')) {
			config.wsUrl = (option.wsUrl || '') + '';
		}

		if (option.hasOwnProperty('udpUrl')) {
			config.udpUrl = (option.udpUrl || '') + '';
		}

		if (option.hasOwnProperty('stunServers')) {
			config.stunServers = (option.stunServers || '') + '';
		}

		if (option.hasOwnProperty('autoLogin')) {
			config.autoLogin = option.autoLogin;
		}
		if (option.hasOwnProperty('autoRTCAnswer')) {
			config.autoRTCAnswer = option.autoRTCAnswer;
		}
		if (option.hasOwnProperty('debug')) {
			config.debug = option.debug;
		}

		return true;
	}


	this.onEvent = function(event) {

	};
	this.onResponseMessage = function(event) {

	};
}

	/**
	 * 连接SOCKET 服务
	 */
	function connect() {

		if (!socket) {

			debug('start agent: ', agent);
			debug('start config: ', config);

			socket = io.connect(config.proxyUrl, {forceNew: true});

			socket.on('connect', function() {
				//onMessage(createAgentStatucOnLineEvent());
				console.log('web-phone--connect的connect')
				getEvent(createAgentStatucOnLineEvent());
			});

			socket.on('connect_error', function(data) {
				socket = null;
				var errorCode = '-500';
				var errorDesc = 'Err_IContact_' + (data ? data.type || 'TransportError' : 'TransportError');
				var errormsg = '网络连接失败，请重新登录！';
				//onMessage(createAgnetErrorEvent(errorCode, errorDesc));
				getEvent(createAgnetErrorEvent(errorCode, errorDesc, errormsg));
			});

			socket.on('disconnect', function() {
				socket = null;
				//onMessage(createAgentStatucOffLineEvent());
				getEvent(createAgentStatucOffLineEvent());
			});

			socket.on('message', function(message) {
				console.log('web-phone--connect的message')
				//内部流转
				onMessage(message);
			});
		}
	}

	/**
	 * 发送命令
	 * @param command
	 * @returns {boolean}
	 */
	function sendCommand(command) {
		if (isOnline) {

			debug('send command:', command);

			socket.emit('command', command);

			return true;
		}
		return false;
	}
	/**
	 * 回调事件
	 * @param event
	 */
	function getEvent(event){
		var that = this;
		try {
			if (isFunction(self.onEvent)) {
				//agent.status = currStatus;
				self.onEvent(event);
				if(isObject(event)){
					switch (event.MessageID) {
						case Evt_AgentStatus_Login:
						case Evt_AgentStatus_Logout:
							onAgentEvent(event);
							break;
						case Evt_AgentStatus_Init:
							isOnline = true;
							onAgentAutoLoginEvent(event);
							break;
						case Evt_AgentStatus_Unkown:
						case Evt_AgentStatus_noAnswer:
							isOnline = false;
							break;
						case Evt_AgentStatus_Consulted:
							onSingleStep(event);
							break;
						default:
							console.log('-----defaulytttt--', event)
							break;
					}
				}
			}
		} catch (error) {
			console.log('getEVENT---', error)
		}
		
	}


	/**
	 * 坐席自动登录
	 */
	function onAgentAutoLoginEvent() {

		// 自动签入
		if (config.autoLogin && agent.status == -1) {
			self.login();
		}

		// 重连自动签入
		if (agent.isLogin) {

			clearLoginTimer()
			self.login();

			// 每6秒重试一次
			loginTimer = setInterval(function() {
				self.login();
			}, 6000);
		}
	}

	function onAgentEvent(event) {

		switch (event.MessageID) {
			case Evt_AgentStatus_Login:
				onAgentLogin(event);
				break;
			case Evt_AgentStatus_Logout:
				onAgentLogout(event);
				break;
		}
	}

	function onAgentLogin(event) {

		if (loginTimer) {
			clearInterval(loginTimer);
		}
		agent.isLogin = true;
		if(option.agentType==='5'){
			webRTCClient.login();
		}
	}

	function onAgentLogout(event) {
		agent.isLogin = false;
		if(option.agentType==='5'){
			webRTCClient.logout();
		}

	}

	function onSingleStep(event) {
		if(singleStepType === 1 && event.CallDetailEvent  === 'CA_CALL_EVENT_CONSULT_CONNECTED_OP'){

			self.doAdressShift();

		}else if(singleStepType === 2 && event.CallDetailEvent  === 'CA_CALL_EVENT_CONSULT_CONNECTED_OP'){

			self.doMeeting();
		}

	}

	function setDefault() {

		for (var key in agentDefault) {
			if (agent[key] == undefined) {
				agent[key] = agentDefault[key];
			}
		}

		for (var key in configDefault) {
			if (config[key] == undefined) {
				config[key] = configDefault[key];
			}
		}
	}

	//清除循环登录任务
	function clearLoginTimer(){
		if(loginTimer){
			clearInterval(loginTimer);
		}
	}
	//获取socket信息
	function getSocketInfo(){
		return socket;
	}


	/**
	 * 消息处理
	 * @param message
	 */
	function onMessage(message) {

		debug('received message:', message);

		if (!message || !message.MessageID) {
			return;
		}

		if (message.MessageID.substring(0, 3) === 'Evt'&&message.MessageID!='Evt_null') {  // 有事件的消息
			if (typeof(message.EventType) != "undefined") {
				getEvent(message)
			}
		} else if (message.MessageID.substring(0, 4) === 'Resp') {  // 响应消息（操作成功/操作失败）
			onResponse(message);
		}

	}

	/**
	 * 接口响应数据
	 * @param response
	 */
	function onResponse(response) {
		console.log('响应数据------onResponse', response)
		switch (response.MessageID) {
			case Resp_IContact_AgentLogin:
				onAgentLoginResponse(response);
				break;
			case Resp_IContact_AgentLogout:
				onAgentLogoutResponse(response);
				break;
			case Resp_IContact_GetAgentData:
				onAgentListData(response);
				break;
			case Resp_IContact_GetDialCaller:
				onAgentDialCallerData(response);
				break;
			case Resp_IContact_GetAgentState:
				onAgentState(response);
				break;
			case Resp_IContact_Listen:
				onAgentListenResponse(response);
				break;
			case Resp_IContact_GetAssociateData:
				onGetCallData(response);
				break;
			case Resp_IContact_Whisper:
				onWhisperData(response);
				break;
			case Resp_IContact_Whisper:
				onWhisperData(response);
				break;
			default:
				if (response && response.code && response.MessageID) {
					console.log('响应数据----default--response', response);
				}
		}
		self.onResponseMessage(response)

	}

	function onAgentLoginResponse(response) {
		agent.isLogin = true;
		if(response.code == 200){
			clearLoginTimer();
			agent.isLogin = true;
			if(option.agentType==='5'){
				webRTCClient.login();
			}
		}
	}
	function onAgentLogoutResponse(response) {
		agent.isLogin = false;
		if(response.code == 200){
			clearLoginTimer();
		}
	}

	function onAgentListData(response) {

		if (isFunction(self.onAgentListData)) {
			self.onAgentListData(response.data);
		}

	}
	function onAgentState(response) {

		if (isFunction(self.onAgentState)) {
			var currStatus =  response.state;
			agent.status = currStatus;
			self.onAgentState(currStatus);
		}

	}
	function onAgentDialCallerData(response) {

		if (isFunction(self.onAgentDialCallerData)) {
			self.onAgentDialCallerData(response.data);
		}

	}

	function onAgentListenResponse(response) {
		if(response.code != 200){

			alert(response.msg)
		}
	}
	function onGetCallData(response) {

		if (isFunction(self.onGetCallData)) {
			self.onGetCallData(response);
		}

	}
	function onWhisperData(response) {

		if (isFunction(self.onWhisperData)) {
			self.onWhisperData(response);
		}

	}


	// 状态控制命令
	var Cmd_IContact_AgentLogin = 'Cmd_IContact_AgentLogin';//登录
	var Cmd_IContact_AgentLogout = 'Cmd_IContact_AgentLogout';//登出
	var Cmd_IContact_AgentNotReady = 'Cmd_IContact_AgentNotReady';//置忙
	var Cmd_IContact_AgentReady = 'Cmd_IContact_AgentReady';//置闲

	// 呼叫控制命令
	var Cmd_IContact_MakeCall = 'Cmd_IContact_MakeCall';//外呼
	var Cmd_IContact_AnswerCall = 'Cmd_IContact_AnswerCall';//应答
	var Cmd_IContact_HangupCall = 'Cmd_IContact_HangupCall';//挂断
	var Cmd_IContact_HoldCall = 'Cmd_IContact_HoldCall';//保持
	var Cmd_IContact_RetrieveCall = 'Cmd_IContact_RetrieveCall';//接回
	var Cmd_IContact_TransferCall = 'Cmd_IContact_TransferCall';//转接
	var Cmd_IContact_ConsultCall = 'Cmd_IContact_ConsultCall';//咨询
	var Cmd_IContact_ConsultReconnect = 'Cmd_IContact_ConsultReconnect';//咨询接回
	var Cmd_IContact_SendDTMF = 'Cmd_IContact_SendDTMF';
	var Cmd_IContact_TransferIVR = 'Cmd_IContact_TransferIVR';//转接IVR
	var Cmd_IContact_AssistService = 'Cmd_IContact_AssistService';//坐席协作
	var Cmd_IContact_ConferenceCall = 'Cmd_IContact_ConferenceCall';//会议

	// 质检命令
	var Cmd_IContact_Listen = 'Cmd_IContact_Listen';//监听
	var Cmd_IContact_ForceInsert = 'Cmd_IContact_ForceInsert';//强插
	var Cmd_IContact_ForceHangup = 'Cmd_IContact_ForceHangup';//强拆
	var Cmd_IContact_Whisper = 'Cmd_IContact_Whisper';//密语


	// 随路数据命令
	var Cmd_IContact_SetAssociateData = 'Cmd_IContact_SetAssociateData';
	var Cmd_IContact_GetAssociateData = 'Cmd_IContact_GetAssociateData';

	// 其他命令
	var Cmd_IContact_GetAgentState = 'Cmd_IContact_GetAgentState';
	var Cmd_IContact_GetAgentList = 'Cmd_IContact_GetAgentList';//座席列表
	var Cmd_IContact_GetDialCaller = 'Cmd_IContact_GetDialCaller';//获取外显号码
	var Cmd_IContact_Reset = 'Cmd_IContact_Reset';//重置




	// 响应消息
	var Resp_IContact_AgentLogin = 'Resp_IContact_AgentLogin';
	var Resp_IContact_AgentLogout = 'Resp_IContact_AgentLogout';
	var Resp_IContact_GetCallData = 'Resp_IContact_GetCallData';
	var Resp_IContact_GetAgentState = 'Resp_IContact_GetAgentState';
	var Resp_IContact_GetAgentData = 'Resp_IContact_GetAgentData';//坐席人员
	var Resp_IContact_GetDialCaller = 'Resp_IContact_GetDialCaller';//坐席外线号码
	var Resp_IContact_Listen = 'Resp_IContact_Listen';//监听
	var Resp_IContact_GetAssociateData = 'Resp_IContact_GetAssociateData';//获取随路数据
	var Resp_IContact_Whisper = 'Resp_IContact_Whisper';//密语


	//坐席回调事件
	var Evt_AgentStatus_Login = 'Evt_AgentStatus_Login';//登录
	var Evt_AgentStatus_Logout = 'Evt_AgentStatus_Logout';//登出
	var Evt_AgentStatus_Consulted = 'Evt_AgentStatus_Consulted';//咨询接通
	var Evt_AgentStatus_Init = 'Evt_AgentStatus_Init';//系统状态初始化
	var Evt_AgentStatus_Unkown = 'Evt_AgentStatus_Unkown';//系统状态错误
	var Evt_AgentStatus_SIPUnkown = 'Evt_AgentStatus_SIPUnkown';//SIP系统状态错误
	var Evt_AgentStatus_noAnswer = 'Evt_AgentStatus_noAnswer';//系统状态无应答



	function createAgentStatucOnLineEvent() {
		return {
			MessageID : Evt_AgentStatus_Init,
			Key_IContact_TimeStamp : currentTime()
		}
	}

	function createAgentStatucOffLineEvent() {
		return {
			MessageID : Evt_AgentStatus_noAnswer,
			Key_IContact_TimeStamp : currentTime()
		}
	}

	function createAgnetErrorEvent(errorCode, errorDesc, errorMsg) {
		return {
			MessageID: Evt_AgentStatus_Unkown,
			Key_IContact_ErrorCode: errorCode + '',
			Key_IContact_ErrorDesc: errorDesc + '',
			Key_IContact_TimeStamp: currentTime(),
			Key_IContact_ErrorMsg: errorMsg + '',
		};
	}

	function createAgnetSIPErrorEvent(errorCode, errorDesc, errorMsg) {
		return {
			MessageID: Evt_AgentStatus_SIPUnkown,
			Key_IContact_ErrorCode: errorCode + '',
			Key_IContact_ErrorDesc: errorDesc + '',
			Key_IContact_TimeStamp: currentTime(),
			Key_IContact_ErrorMsg: errorMsg + '',
		};
	}

	function createLoginCommand(agent) {
		return {
			MessageID : Cmd_IContact_AgentLogin,
			Key_IContact_AgentID : agent.agentId,
			Key_IContact_AgentDN : agent.agentDn,
			Key_IContact_AgentName : agent.agentName,
			Key_IContact_AgentType : agent.agentType,
			Key_IContact_ACDAgentPassword : agent.acdAgentPassword,
			// Key_IContact_isForced: 1 + ''  // 强制登录、
		};
	}

	function createLogoutCommand(agentId) {
		return {
			MessageID : Cmd_IContact_AgentLogout,
			Key_IContact_AgentID : agentId + ''
		};
	}

	function createNotReadyCommand(agentId) {
		return {
			MessageID : Cmd_IContact_AgentNotReady,
			Key_IContact_AgentID : agentId + ''
		};
	}

	function createReadyCommand(agentId) {
		return {
			MessageID : Cmd_IContact_AgentReady,
			Key_IContact_AgentID : agentId + ''
		};
	}

	function createMakeCallCommand(agentId, destType, destDesc, callingParty) {
		return {
			MessageID : Cmd_IContact_MakeCall,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_DestType : parseInt(destType),
			Key_IContact_DestDesc : (destDesc || '') + '',
			Key_IContact_CallingParty : (callingParty || '') + '',
			Key_IContact_ACDAgentPassword : agent.acdAgentPassword
		};
	}

	function createAnswerCommand(agentId, agentDn) {
		return {
			MessageID : Cmd_IContact_AnswerCall,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_DeviceDN : agentDn + ''
		};
	}

	function createHangupCommand(agentId, agentDn) {
		return {
			MessageID : Cmd_IContact_HangupCall,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_DeviceDN : agentDn + ''
		};
	}

	function createHoldCommand(agentId, agentPwd) {
		return {
			MessageID : Cmd_IContact_HoldCall,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + ''
		};
	}

	function createRetrieveCommand(agentId, agentPwd) {
		return {
			MessageID : Cmd_IContact_RetrieveCall,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + ''
		};
	}

	function createAdressShiftCommand(agentId, agentPwd) {
		return {
			MessageID : Cmd_IContact_TransferCall,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + ''
		};
	}


	function createConsultingCommand(agentId, agentPwd, sessionId, consultType, destDesc) {
		return {
			MessageID : Cmd_IContact_ConsultCall,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + '',
			Key_IContact_SessionID : sessionId,
			Key_IContact_ConsultType : parseInt(consultType),
			Key_IContact_ConsultNumber : destDesc + '',
			Key_IContact_TimeStamp : (new Date()).valueOf()+ ''
		};
	}

	function createMeetingCommand(agentId, agentPwd) {
		return {
			MessageID : Cmd_IContact_ConferenceCall,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + ''
		};
	}

	function createWhisperCommand(agentId,agentPwd,sessionId,destType) {
		return {
			MessageID : Cmd_IContact_Whisper,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + '',
			Key_IContact_SessionID : sessionId + '',
			Key_IContact_IsWhisperApi: destType + ''
		};
	}
	function createAssistServiceCommand(agentId,agentPwd,dataKey, dataValue) {
		return {
			MessageID : Cmd_IContact_AssistService,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + '',
			Key_IContact_ServiceDataKey : dataKey + '',
			Key_IContact_ServiceDataValue: dataValue + ''
		};
	}

	function createReconnectCallCommand(agentId, agentDn) {
		return {
			MessageID : Cmd_IContact_ConsultReconnect,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_DeviceDN : agentDn + ''
		};
	}

	function createSendDTMFCommand(agentId, agentDn, DTMF) {
		console.log('发送命令-TMF', agentId, agentDn, DTMF)
		return {
			MessageID : Cmd_IContact_SendDTMF,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_DTMF : DTMF + ''
		};
	}

	function createTransferIVRCommand(entId, agentId,agentPwd, destDesc) {
		return {
			MessageID : Cmd_IContact_TransferIVR,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + '',
			entId : entId + '',
			Key_IContact_CallData : destDesc + ''
		};
	}

	function createListenCommand(agentId, agentPwd, destAgentId) {
		return {
			MessageID : Cmd_IContact_Listen,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + '',
			Key_IContact_DestAgentID : destAgentId+ ''
		};
	}


	function createInsertCommand(agentId) {
		return {
			MessageID : Cmd_IContact_ForceInsert,
			Key_IContact_AgentID : agentId + ''
		};
	}
	function createDropCommand(agentId) {
		return {
			MessageID : Cmd_IContact_ForceHangup,
			Key_IContact_AgentID : agentId + ''
		};
	}

	function createSetCallDataCommand(agentId,sessionId, dataKey, dataValue) {
		return {
			MessageID : Cmd_IContact_SetAssociateData,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_SessionID : sessionId + '',
			Key_IContact_ServiceDataKey : dataKey + '',
			Key_IContact_ServiceDataValue : dataValue + ''
		};
	}

	function createGetCallDataCommand(agentId,sessionId, dataKey) {
		return {
			MessageID : Cmd_IContact_GetAssociateData,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_SessionID : sessionId + '',
			Key_IContact_ServiceDataKey : dataKey + ''
		};
	}

	function createGetAgentStateCommand(entId,agentId,agentPwd,state) {
		return {
			MessageID : Cmd_IContact_GetAgentState,
			entId : entId+ '',
			Key_IContact_AgentID : agentId + '',
			Key_IContact_ACDAgentPassword : agentPwd + '',
			Key_IContact_State : state + ''
		};
	}

	function createAgentListCommand(entId, agentState, agentId) {
		return {
			MessageID : Cmd_IContact_GetAgentList,
			entId : entId+ '',
			Key_IContact_agentState: agentState + '',
			Key_IContact_AgentID : agentId + ''
		};
	}

	function createAgentDialCallerCommand(entId,agentId) {
		return {
			MessageID : Cmd_IContact_GetDialCaller,
			entId : entId+ '',
			Key_IContact_AgentID : agentId + ''
		};
	}

	function createAgentStateResetCommand(agentId,destDesc) {
		return {
			MessageID : Cmd_IContact_Reset,
			Key_IContact_AgentID : agentId + '',
			Key_IContact_AgentStatus : destDesc + ''
		};
	}

	function isObject(obj) {
		var type = typeof obj;
		return !!obj && (type == 'object' || type == 'function');
	}
	function isFunction(obj) {
		return isObject(obj) && Object.prototype.toString.call(obj) == '[object Function]';
	}
	function debug(message, data) {
		if (config.debug) {
			showMessage(message, data);
		}
	}
	function showMessage(message, data) {
		if (window.console && console.log) {
			if (isObject(data)) {
				if (JSON && JSON.stringify) {
					console.log(message, JSON.stringify(data, null, 2),	getNowTime());
				} else {
					console.log(message, data, getNowTime());
				}
			} else {
				console.log(message, data, getNowTime());
			}
		}
	}

	function currentTime() {

		function f(n) {
			return n < 10 ? '0' + n : n;
		}

		function f2(n) {
			if (n < 10) return '00' + n;
			return n < 100 ? '0' + n : n;
		}

		var now = new Date();

		return now.getFullYear() + '-' +
			f(now.getMonth() + 1) + '-' +
			f(now.getDate()) + ' ' +
			f(now.getHours()) + ':' +
			f(now.getMinutes()) + ':' +
			f(now.getSeconds()) + '.' +
			f2(now.getMilliseconds());
	}

	function getNowTime () {
		let now = new Date();
		let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
		let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
		let today = now.getDate(); //获取当前日(1-31)
		let hour = now.getHours(); //获取当前小时数(0-23)
		let minute = now.getMinutes(); //获取当前分钟数(0-59)
		let second = now.getSeconds(); //获取当前秒数(0-59)
		let nowTime = ''
		nowTime = year + '-' + fillZero(month) + '-' + fillZero(today) + ' ' + fillZero(hour) + ':' +
		  fillZero(minute) + ':' + fillZero(second)
		return nowTime
	}
	  
	function fillZero (str) {
		var realNum;
		if (str < 10) {
			realNum = '0' + str;
		} else {
			realNum = str;
		}
		return realNum;
	}

	return webAgent;

}))